import { getWechat, userLogin, getUserInfor } from '../../api/index'
let app = getApp()
let component = {
  properties: {
    sourceid: {
      type: Number
    }
  },
  data: {
    hideAuth: true
  },
  attached () {
    this.init()
  },
  methods: {
    init () {
      this.userOpenid()
        .then(() => {
          this.userSetting()
        })
        .catch((er) => {
        })
    },
    userOpenid () {
      return new Promise((resolve, reject) => {
        // 登录
        wx.login({
          success: res => {
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            if (res.code) {
              // 获取用户信息
              getUserInfor({ code: res.code }).then(
                resolves => {
                  wx.setStorageSync('openid', resolves.data.openid)
                  resolve()
                }
              ).catch(err => {
                reject(err)
              })
            }
          }
        })
      })
    },
    userSetting () {
      // 获取用户信息
      wx.getSetting({
        success: res => {
          if (res.authSetting['scope.userInfo']) {
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
            this.userInfo()
          } else {
            this.setData({
              hideAuth: false
            })
          }
        }
      })
    },
    userInfo () {
      wx.getUserInfo({
        success: res => {
          this.nickName = res.userInfo.nickName
          wx.setStorageSync('avatarUrl', res.userInfo.avatarUrl)
          wx.setStorageSync('nickName', res.userInfo.nickName)
          wx.setStorageSync('city', res.userInfo.city || res.userInfo.country)
          // 可以将 res 发送给后台解码出 unionId
          app.globalData.userInfo = res.userInfo
          this.getWx(res)
        }
      })
    },
    bindGetUserInfo (e) {
      if (e.detail.errMsg.indexOf('ok') !== -1) {
        app.globalData.userInfo = e.detail.userInfo
        this.getWx(e.detail)
        wx.setStorageSync('formIDCount', 2)
        wx.setStorageSync('nickName', e.detail.userInfo.nickName)
        wx.setStorageSync('city', e.detail.userInfo.city || e.detail.userInfo.country)
      } else {
        wx.showToast({
          title: '请同意授权',
          icon: 'none'
        })
      }
    },
    // 用户授权
    getWx (res) {
      const openid = wx.getStorageSync('openid')
      // 用户授权
      getWechat({
        encryptedData: res.encryptedData,
        iv: res.iv,
        rawData: res.rawData,
        signature: res.signature,
        openid
      }).then(
        res2 => {
          // console.log(res2)
          userLogin({ openid, wx_info: res2.data, source_uid: this.data.sourceid ? this.data.sourceid : '' }).then(
            res3 => {
              // console.log(res3)
              if (res3.data.code && res.data.code < 0) {
                wx.showToast({
                  title: res3.data.message,
                  icon: 'none'
                })
              } else {
                this.setData({
                  hideAuth: true
                })
                wx.setStorageSync('token', res3.data.token)
                wx.setStorageSync('uid', res3.data.member_info.user_info.uid)
                this.triggerEvent('changeAuthStatus', { status: false, getRed: res3.data.member_info.user_info.is_new_red, uid: res3.data.member_info.user_info.uid })
              }
            }
          )
        }
      )
    }
  }
}
Component(component)
